using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FytSoa.Common;
using FytSoa.Core.Model;
using FytSoa.Extensions;
using FytSoa.Service.DtoModel;
using FytSoa.Service.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using FytSoa.Core.Model.TourGuide;
using System.IO;
using System.Text;
using FytSoa.Extensions.Xcx;

namespace FytSoa.Api.Controllers.TourGuide
{
    [JwtAuthorize(Roles = "Admin")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TourGuideController : ControllerBase
    {
        private ITourGuideOrderService _orderService;
        public TourGuideController(ITourGuideOrderService orderService)
        {
            _orderService = orderService;
        }

        [HttpGet]
        public async Task<ApiResult<Page<TourGuideOrder>>> List([FromQuery]PageParm param)
        {
            return await _orderService.GetPageWhereList(param);
        }

        [HttpPost]
        public async Task<ApiResult<string>> CreateTxt([FromBody]TourGuideOrder model)
        {
            var res = new ApiResult<string>() { statusCode = 500 };
            var txt = string.Empty;
            //读取模板
            var template = FileHelperCore.MapPath("/wwwroot/tempfile/ordertemp.txt");
            try
            {
                txt = await System.IO.File.ReadAllTextAsync(template);
                //替换字符串
                txt = txt.Replace("${Order}", model.Number);
                txt = txt.Replace("${UserName}", model.Member.NickName);
                txt = txt.Replace("${UserMobile}", model.Member.Mobile);
                txt = txt.Replace("${ServerCity}", model.Types == 1 ? "国内航班" : "国际航班");
                //txt = txt.Replace("${OrderStatus}", OrderStatusByName(model.ServiceStatus));
                txt = txt.Replace("${ServerDate}", model.ServiceData.ToShortDateString());
                txt = txt.Replace("${FlightNumber}", model.FlightNumber);
                txt = txt.Replace("${HbName}", GetHbNameAndTime(model)[0]);
                txt = txt.Replace("${HbTime}", GetHbNameAndTime(model)[1]);
                txt = txt.Replace("${PeopleNumber}", model.PeopleNumber.ToString());
                //txt = txt.Replace("${Price}", model.Price.ToString());
                txt = txt.Replace("${DriverPhone}", model.DriverPhone);
                //txt = txt.Replace("${BackStatus}", BackStatusByName(model.BackStatus));
                txt = txt.Replace("${Summary}", model.Summary);
                txt = txt.Replace("${ServerMold}", OrderServerMold(model.Mold, model.Types));
                //txt = txt.Replace("${AddTime}", model.AddTime.ToString());
                var lxr = string.Empty;
                foreach (var item in model.ContactUs)
                {
                    lxr += "姓名：" + item.name + "                   联系方式：" + item.phone + "      ";
                }
                txt = txt.Replace("${ContactUs}", lxr);
                //创建文件
                FileStream fs = null;
                var newsTxt = FileHelperCore.MapPath("/wwwroot/tempfile/txt/" + model.Number + ".txt");
                if (!System.IO.File.Exists(newsTxt))
                {
                    fs = new FileStream(newsTxt, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                }
                else
                {
                    fs = new FileStream(newsTxt, System.IO.FileMode.Open, System.IO.FileAccess.Write);
                }
                using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8))
                {
                    await sr.WriteAsync(txt);
                }
                fs.Close();
                res.statusCode = 200;
                res.data = model.Number + ".txt"; ;
            }
            catch (System.Exception ex)
            {
                res.message = ex.Message;
            }
            return res;
        }
        string OrderServerMold(int status, int types)
        {
            var str = string.Empty;
            switch (status)
            {
                case 1: str = "普通接机服务"; break;
                case 2: str = "普通送机服务"; break;
                case 3: str = "VIP接机服务"; break;
                case 4: str = "VIP送机服务"; break;
                case 5: str = "登机口接机服务"; break;
                case 6: str = "登机口送机服务"; break;
                case 7: str = types == 1 ? "安检快速通道" : "联检快速通道"; break;
                case 8: str = "贵宾休息室"; break;
            }
            return str;
        }
        List<string> GetHbNameAndTime(TourGuideOrder model)
        {
            var res = new List<string>();
            string name = "到达", time = model.LandTime.Hour + ":" + model.LandTime.Minute;
            if (model.Mold == 2 || model.Mold == 4 || model.Mold == 6 || model.Mold == 7 || model.Mold == 8)
            {
                name = "起飞";
                time = model.TakeOffTime.Hour + ":" + model.TakeOffTime.Minute;
            }
            res.Add(name);
            res.Add(time);
            return res;
        }
        string OrderStatusByName(int status)
        {
            var str = string.Empty;
            switch (status)
            {
                case 1: str = "已提交"; break;
                case 2: str = "服务中"; break;
                case 3: str = "已完成"; break;
                case 4: str = "已退款"; break;
            }
            return str;
        }
        string BackStatusByName(int status)
        {
            var str = string.Empty;
            switch (status)
            {
                case 0: str = "无"; break;
                case 1: str = "申请退款"; break;
                case 2: str = "已退款"; break;
                case 3: str = "已驳回"; break;
            }
            return str;
        }

        [HttpPost]
        public async Task<ApiResult<string>> UpdateStatus([FromBody]TourGuideOrderStatusParm param)
        {
            var str = Utils.StrToListString(param.guid);
            var list = await _orderService.GetListAsync(m => str.Contains(m.Guid), m => m.AddTime, DbOrderEnum.Desc);
            foreach (var item in list.data)
            {
                item.ServiceStatus = param.status;
                if (param.status != 4) continue;
                item.BackStatus = 2;
                item.BackProgress.Add(new ServiceBackProgress() { info = "同意退款~", times = DateTime.Now });
            }
            return await _orderService.UpdateAsync(list.data);
        }

        [HttpPost, ApiAuthorize(Modules = "TgOrderList", Methods = "BackMoney", LogType = LogEnum.STATUS)]
        public async Task<ApiResult<string>> BackMoney([FromBody]TourGuideOrderStatusParm param)
        {
            var str = Utils.StrToListString(param.guid);
            var list = await _orderService.GetListAsync(m => str.Contains(m.Guid), m => m.AddTime, DbOrderEnum.Desc);
            foreach (var item in list.data)
            {
                item.BackStatus = 2;
                item.ServiceStatus = param.status;
                if (param.status != 4) continue;
                item.BackProgress.Add(new ServiceBackProgress() { info = "同意退款~", times = DateTime.Now });
            }
            return await _orderService.UpdateAsync(list.data);
        }

        [HttpPost, ApiAuthorize(Modules = "TgOrderList", Methods = "Delete", LogType = LogEnum.DELETE)]
        public async Task<ApiResult<string>> Delete([FromBody]ParmString param)
        {
            return await _orderService.DeleteAsync(param.parm);
        }
    }
}
